// REST架构象棋AI对战 - 完整版JavaScript代码
// 支持REST API和传统API双模式

class XiangqiGame {
  constructor() {
    this.canvas = document.getElementById("canvas");
    this.ctx = this.canvas.getContext("2d");
    this.radius = 23;
    this.chunk = 50;
    this.selectedPiece = null;
    this.currentPlayer = "red"; // red 或 black
    this.gameState = "playing"; // playing, check, checkmate, stalemate
    this.gameMode = "human_vs_ai"; // human_vs_ai 或 human_vs_human
    this.winner = null;
    this.inCheck = false;
    this.gameMessage = "游戏进行中";
    this.validMoves = []; // 存储当前选中棋子的合法移动

    // REST API 配置
    this.apiBaseUrl = "http://8.138.255.35:5000"; // 可配置API基础URL
    this.restApiBaseUrl = "http://8.138.255.35:5000/api/v1"; // REST API基础URL
    this.gameId = null;
    this.useRestApi = true; // 开关：是否使用REST API

    // 初始化棋盘
    this.initBoard();
    this.initPieces();
    this.addEventListeners();
    this.draw();
    this.updateGameStatus("playing", null, "游戏进行中", false);

    // 添加模式切换按钮
    this.addModeToggleButton();
    
    // 初始化REST游戏
    if (this.useRestApi) {
      this.initRestGame();
    }
  }

  // ===== REST API 相关方法 =====

  async initRestGame() {
    try {
      const response = await fetch(`${this.restApiBaseUrl}/games`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          mode: this.gameMode,
          player_color: 'red'
        })
      });
      
      const result = await response.json();
      if (result.success) {
        this.gameId = result.data.id;
        console.log(`🎮 REST游戏创建成功，ID: ${this.gameId}`);
        this.showMessage('REST API模式已启用', 'success');
      } else {
        throw new Error(result.error || 'REST游戏创建失败');
      }
    } catch (error) {
      console.warn('⚠️ REST API不可用，回退到传统模式:', error);
      this.useRestApi = false;
      this.showMessage('已切换到传统API模式', 'warning');
    }
  }

  async restApiCall(endpoint, method = 'GET', data = null) {
    try {
      const config = {
        method: method,
        headers: {
          'Content-Type': 'application/json',
        }
      };

      if (data && (method === 'POST' || method === 'PUT')) {
        config.body = JSON.stringify(data);
      }

      const response = await fetch(`${this.restApiBaseUrl}${endpoint}`, config);
      const result = await response.json();
      
      return result;
    } catch (error) {
      console.error('REST API调用失败:', error);
      throw error;
    }
  }

  async checkApiCompatibility() {
    try {
      const result = await this.restApiCall('/system/status', 'GET');
      if (result.success) {
        console.log('✅ REST API可用:', result.data.api_version);
        return true;
      }
    } catch (error) {
      console.log('⚠️ REST API不可用，使用传统模式');
    }
    return false;
  }

  toggleApiMode() {
    this.useRestApi = !this.useRestApi;
    console.log(`🔄 API模式切换为: ${this.useRestApi ? 'REST' : '传统'}`);
    
    if (this.useRestApi) {
      this.initRestGame();
    }
    
    this.showMessage(`已切换到${this.useRestApi ? 'REST' : '传统'}API模式`);
    
    // 更新按钮文本
    const toggleBtn = document.getElementById("api-toggle-btn");
    if (toggleBtn) {
      toggleBtn.textContent = this.useRestApi ? "切换到传统API" : "切换到REST API";
    }
  }

  // ===== 棋盘绘制相关方法 =====

  initBoard() {
    this.drawBoard();
  }

  drawBoard() {
    const ctx = this.ctx;
    const chunk = this.chunk;

    // 清空画布
    ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);

    // 设置线条样式
    ctx.strokeStyle = "#000";
    ctx.lineWidth = 1;

    // 绘制横线
    for (let i = 0; i <= 9; i++) {
      ctx.beginPath();
      ctx.moveTo(chunk, chunk + i * chunk);
      ctx.lineTo(9 * chunk, chunk + i * chunk);
      ctx.stroke();
    }

    // 绘制竖线
    for (let i = 0; i <= 8; i++) {
      // 上半部分
      ctx.beginPath();
      ctx.moveTo(chunk + i * chunk, chunk);
      ctx.lineTo(chunk + i * chunk, 5 * chunk);
      ctx.stroke();

      // 下半部分
      ctx.beginPath();
      ctx.moveTo(chunk + i * chunk, 6 * chunk);
      ctx.lineTo(chunk + i * chunk, 10 * chunk);
      ctx.stroke();
    }

    // 绘制九宫格斜线
    // 上方九宫格
    ctx.beginPath();
    ctx.moveTo(4 * chunk, chunk);
    ctx.lineTo(6 * chunk, 3 * chunk);
    ctx.stroke();

    ctx.beginPath();
    ctx.moveTo(6 * chunk, chunk);
    ctx.lineTo(4 * chunk, 3 * chunk);
    ctx.stroke();

    // 下方九宫格
    ctx.beginPath();
    ctx.moveTo(4 * chunk, 8 * chunk);
    ctx.lineTo(6 * chunk, 10 * chunk);
    ctx.stroke();

    ctx.beginPath();
    ctx.moveTo(6 * chunk, 8 * chunk);
    ctx.lineTo(4 * chunk, 10 * chunk);
    ctx.stroke();
  }

  initPieces() {
    // 初始化棋子位置
    this.pieces = [
      // 红方棋子 (下方)
      { id: 8, text: "車", type: "red", x: 8, y: 9 },
      { id: 7, text: "馬", type: "red", x: 7, y: 9 },
      { id: 6, text: "相", type: "red", x: 6, y: 9 },
      { id: 5, text: "仕", type: "red", x: 5, y: 9 },
      { id: 4, text: "帅", type: "red", x: 4, y: 9 },
      { id: 3, text: "仕", type: "red", x: 3, y: 9 },
      { id: 2, text: "相", type: "red", x: 2, y: 9 },
      { id: 1, text: "馬", type: "red", x: 1, y: 9 },
      { id: 0, text: "車", type: "red", x: 0, y: 9 },
      { id: 10, text: "炮", type: "red", x: 7, y: 7 },
      { id: 9, text: "炮", type: "red", x: 1, y: 7 },
      { id: 15, text: "兵", type: "red", x: 8, y: 6 },
      { id: 14, text: "兵", type: "red", x: 6, y: 6 },
      { id: 13, text: "兵", type: "red", x: 4, y: 6 },
      { id: 12, text: "兵", type: "red", x: 2, y: 6 },
      { id: 11, text: "兵", type: "red", x: 0, y: 6 },

      // 黑方棋子 (上方)
      { id: 16, text: "車", type: "black", x: 0, y: 0 },
      { id: 17, text: "馬", type: "black", x: 1, y: 0 },
      { id: 18, text: "象", type: "black", x: 2, y: 0 },
      { id: 19, text: "士", type: "black", x: 3, y: 0 },
      { id: 20, text: "将", type: "black", x: 4, y: 0 },
      { id: 21, text: "士", type: "black", x: 5, y: 0 },
      { id: 22, text: "象", type: "black", x: 6, y: 0 },
      { id: 23, text: "馬", type: "black", x: 7, y: 0 },
      { id: 24, text: "車", type: "black", x: 8, y: 0 },
      { id: 25, text: "炮", type: "black", x: 1, y: 2 },
      { id: 26, text: "炮", type: "black", x: 7, y: 2 },
      { id: 27, text: "卒", type: "black", x: 0, y: 3 },
      { id: 28, text: "卒", type: "black", x: 2, y: 3 },
      { id: 29, text: "卒", type: "black", x: 4, y: 3 },
      { id: 30, text: "卒", type: "black", x: 6, y: 3 },
      { id: 31, text: "卒", type: "black", x: 8, y: 3 },
    ];
  }

  draw() {
    this.drawBoard();
    this.drawPieces();
    this.drawValidMoves();

    if (this.selectedPiece) {
        this.highlightSelectedPiece();
    }

    // 如果有王被将军，添加警告效果
    if (this.inCheck) {
      this.highlightCheck();
    }
  }

  drawPieces() {
    const ctx = this.ctx;
    const chunk = this.chunk;
    const radius = this.radius;

    this.pieces.forEach((piece) => {
      if (piece.x === 99 || piece.y === 99) return; // 被吃的棋子不绘制

      const x = chunk + piece.x * chunk;
      const y = chunk + piece.y * chunk;

      // 绘制棋子背景圆
      ctx.beginPath();
      ctx.arc(x, y, radius, 0, 2 * Math.PI);
      ctx.fillStyle = piece.type === "red" ? "#FFE4B5" : "#F5F5DC";
      ctx.fill();
      ctx.strokeStyle = "#000";
      ctx.lineWidth = 2;
      ctx.stroke();

      // 绘制棋子文字
      ctx.fillStyle = piece.type === "red" ? "#FF0000" : "#000000";
      ctx.font = "18px serif";
      ctx.textAlign = "center";
      ctx.textBaseline = "middle";
      ctx.fillText(piece.text, x, y);
    });
  }

  drawValidMoves() {
    if (!this.validMoves || this.validMoves.length === 0) return;

    const ctx = this.ctx;
    const chunk = this.chunk;

    this.validMoves.forEach(move => {
      const x = chunk + move.x * chunk;
      const y = chunk + move.y * chunk;
    });
  }

  highlightSelectedPiece() {
    if (!this.selectedPiece) return;

    const ctx = this.ctx;
    const chunk = this.chunk;
    const x = chunk + this.selectedPiece.x * chunk;
    const y = chunk + this.selectedPiece.y * chunk;

    ctx.beginPath();
    ctx.arc(x, y, this.radius + 3, 0, 2 * Math.PI);
    ctx.strokeStyle = "#00FF00";
    ctx.lineWidth = 3;
    ctx.stroke();
  }

  highlightCheck() {
    // 找到被将军的王
    const kingPiece = this.pieces.find(
      (p) =>
        (p.text === "帅" || p.text === "将") &&
        p.type === this.currentPlayer &&
        p.x !== 99 &&
        p.y !== 99
    );

    if (!kingPiece) return;

    const ctx = this.ctx;
    const chunk = this.chunk;
    const x = chunk + kingPiece.x * chunk;
    const y = chunk + kingPiece.y * chunk;

    // 绘制红色警告圈
    ctx.beginPath();
    ctx.arc(x, y, this.radius + 8, 0, 2 * Math.PI);
    ctx.strokeStyle = "#FF0000";
    ctx.lineWidth = 4;
    ctx.stroke();

    // 绘制闪烁效果
    const time = Date.now() % 1000;
    if (time < 500) {
      ctx.beginPath();
      ctx.arc(x, y, this.radius + 12, 0, 2 * Math.PI);
      ctx.strokeStyle = "rgba(255, 0, 0, 0.5)";
      ctx.lineWidth = 2;
      ctx.stroke();
    }
  }

  // ===== 事件处理相关方法 =====

  addEventListeners() {
    this.canvas.addEventListener("click", (e) => {
      if (this.gameState === "checkmate" || this.gameState === "stalemate") {
        return; // 游戏结束，不允许移动
      }

      const rect = this.canvas.getBoundingClientRect();
      const x = e.clientX - rect.left;
      const y = e.clientY - rect.top;
      this.handleClick(x, y);
    });

    document.getElementById("aiMoveBtn").addEventListener("click", () => {
      this.makeAIMove();
    });

    document.getElementById("resetBtn").addEventListener("click", () => {
      this.resetGame();
    });

    document.getElementById("newGameBtn").addEventListener("click", () => {
      this.resetGame();
    });
  }

  handleClick(x, y) {
    if (this.gameState === "checkmate" || this.gameState === "stalemate")
      return;

    if (this.gameState !== "playing" && this.gameState !== "check") return;

    // 根据游戏模式决定是否允许点击
    if (this.gameMode === "human_vs_ai" && this.currentPlayer !== "red") {
      this.showMessage("现在是AI回合，请等待");
      return;
    }

    const chunk = this.chunk;
    const boardX = Math.round((x - chunk) / chunk);
    const boardY = Math.round((y - chunk) / chunk);

    if (boardX < 0 || boardX > 8 || boardY < 0 || boardY > 9) return;

    const clickedPiece = this.pieces.find(
      (p) => p.x === boardX && p.y === boardY && p.x !== 99
    );

    if (this.selectedPiece) {
      // 已选中棋子，尝试移动
      if (clickedPiece && clickedPiece.type === this.currentPlayer) {
        // 点击同方棋子，重新选择
        this.selectedPiece = clickedPiece;
        this.getValidMovesForPiece(clickedPiece);
      } else {
        // 尝试移动到目标位置
        this.attemptMove(this.selectedPiece, boardX, boardY);
      }
    } else {
      // 未选中棋子，选择棋子
      if (clickedPiece && clickedPiece.type === this.currentPlayer) {
        this.selectedPiece = clickedPiece;
        this.getValidMovesForPiece(clickedPiece);
      }
    }

    this.draw();
  }

  async getValidMovesForPiece(piece) {
    // 这里可以调用API获取合法移动，暂时清空
    this.validMoves = [];
    
    if (this.useRestApi && this.gameId) {
      try {
        const result = await this.restApiCall(`/games/${this.gameId}/valid-moves?piece_x=${piece.x}&piece_y=${piece.y}`);
        if (result.success) {
          this.validMoves = result.data.valid_moves || [];
        }
      } catch (error) {
        console.warn('获取合法移动失败:', error);
      }
    }
  }

  // ===== 移动相关方法 =====

  async attemptMove(piece, targetX, targetY) {
    const move = piece.x.toString() + piece.y.toString() + targetX.toString() + targetY.toString();
    const currentState = this.boardToState();

    try {
      let result;
      
      if (this.useRestApi && this.gameId) {
        // 使用REST API
        result = await this.restApiCall(`/games/${this.gameId}/moves`, 'POST', {
          board_state: currentState,
          move: move,
          color: this.currentPlayer,
          // 同时支持新格式
          from: { x: piece.x, y: piece.y },
          to: { x: targetX, y: targetY },
          piece_type: piece.text
        });
        
        if (result.success) {
          console.log(`✅ REST ${this.currentPlayer}方移动成功:`, move);
          this.applyMoveResult(result.data);
        } else {
          throw new Error(result.error || '移动失败');
        }
      } else {
        // 回退到原有API
        const response = await fetch(`${this.apiBaseUrl}/player_move/`, {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
          },
          body: JSON.stringify({
            board: currentState,
            move: move,
            color: this.currentPlayer,
          }),
        });

        result = await response.json();

        if (result.valid) {
          console.log(`✅ ${this.currentPlayer}方移动成功:`, move);
          this.applyLegacyMoveResult(result);
        } else {
          throw new Error(result.message || '移动不合法');
        }
      }

    } catch (error) {
      console.log("❌ 移动失败:", error.message);
      this.updateStatus("移动失败: " + error.message);
      this.selectedPiece = null;
      this.validMoves = [];
      this.showMessage(`移动失败: ${error.message}`);
    }
  }

  async makeAIMove() {
    if (this.currentPlayer !== "black" || 
        this.gameState === "checkmate" || 
        this.gameState === "stalemate") return;

    document.getElementById("aiMoveBtn").disabled = true;
    this.updateStatus("AI思考中...");

    const currentState = this.boardToState();

    try {
      let result;
      
      if (this.useRestApi && this.gameId) {
        // 使用REST API
        result = await this.restApiCall(`/games/${this.gameId}/ai-move`, 'POST', {
          board_state: currentState
        });
        
        if (result.success) {
          console.log("✅ REST AI移动成功:", result.data.move);
          this.applyMoveResult(result.data);
        } else if (result.error === 'no_chess_data' || result.error === 'no_valid_move') {
          console.log("❌ AI无法响应:", result.message);
          if (result.data?.player_mode && result.data?.next_player) {
            this.switchToPlayerControlMode(result.data.next_player);
            this.showMessage(result.message || `请您控制${result.data.next_player === "black" ? "黑" : "红"}方棋子`);
          }
        } else {
          throw new Error(result.error || 'AI移动失败');
        }
      } else {
        // 回退到原有API
        const response = await fetch(`${this.apiBaseUrl}/move/${currentState}`);

        if (response.ok) {
          result = await response.json();
          if (result.move && result.new_state) {
            console.log("✅ AI移动成功:", result.move);
            this.applyLegacyAIMoveResult(result);
          } else {
            this.updateStatus("AI无法找到合适的移动");
          }
        } else {
          const errorData = await response.json();
          console.log("❌ AI无法响应:", errorData);
          if (errorData.player_mode && errorData.next_player) {
            this.switchToPlayerControlMode(errorData.next_player);
            this.showMessage(`AI没有数据，请您控制${errorData.next_player === "black" ? "黑" : "红"}方棋子`);
          } else {
            this.updateStatus("AI移动失败");
          }
        }
      }
    } catch (error) {
      console.error("AI移动请求失败:", error);
      this.switchToPlayerControlMode("black");
      this.showMessage("AI服务器连接失败，请您控制黑方棋子");
    } finally {
      document.getElementById("aiMoveBtn").disabled = false;
    }
  }

  // ===== 结果处理方法 =====

  applyMoveResult(data) {
    // 更新棋盘状态
    if (data.new_board_state) {
      this.applyStateToBoard(data.new_board_state);
    }
    
    // 更新当前玩家
    if (data.current_player) {
      this.currentPlayer = data.current_player;
      this.updatePlayerIndicator(data.current_player);
    }
    
    // 处理游戏状态
    if (data.game_status) {
      this.handleGameStatus(data.game_status);
    }
    
    this.selectedPiece = null;
    this.validMoves = [];
    this.draw();
    
    // 处理下一步逻辑
    this.handleNextMove(data);
  }

  applyLegacyMoveResult(result) {
    this.applyStateToBoard(result.new_state);
    this.selectedPiece = null;
    this.validMoves = [];

    if (result.game_status) {
      this.handleGameStatus(result.game_status);
    }

    if (this.gameMode === "human_vs_ai") {
      if (this.currentPlayer === "red" && 
          (this.gameState === "check" || this.gameState === "playing")) {
        this.currentPlayer = "black";
        this.updatePlayerIndicator("黑方");
        this.draw();
        setTimeout(() => this.makeAIMove(), 500);
      } else if (this.gameState === "check" || this.gameState === "playing") {
        this.currentPlayer = "red";
        this.updatePlayerIndicator("红方");
        this.draw();
      }
    } else {
      if (this.gameState === "playing" || this.gameState === "check") {
        this.currentPlayer = this.currentPlayer === "red" ? "black" : "red";
        this.updatePlayerIndicator(this.currentPlayer);
        this.draw();
        const nextPlayerText = this.currentPlayer === "red" ? "红方" : "黑方";
        this.showMessage(`轮到${nextPlayerText}走棋`);
      }
    }
  }

  applyLegacyAIMoveResult(result) {
    this.applyStateToBoard(result.new_state);

    if (result.game_status) {
      this.handleGameStatus(result.game_status);
    }

    if (this.gameState === "playing" || this.gameState === "check") {
      this.currentPlayer = "red";
      this.updatePlayerIndicator("红方");
    }
    this.draw();
  }

  handleNextMove(data) {
    if (this.gameMode === "human_vs_ai") {
      if (data.current_player === "black" && 
          (this.gameState === "check" || this.gameState === "playing")) {
        // 自动进行AI走棋
        setTimeout(() => this.makeAIMove(), 500);
      }
    } else {
      // 双人模式
      if (this.gameState === "playing" || this.gameState === "check") {
        const nextPlayerText = data.current_player === "red" ? "红方" : "黑方";
        this.showMessage(`轮到${nextPlayerText}走棋`);
      }
    }
  }

  // ===== 游戏状态处理 =====

  handleGameStatus(gameStatus) {
    console.log("🎮 处理游戏状态更新:", gameStatus);
    
    this.gameState = gameStatus.status;
    this.winner = gameStatus.winner;
    this.inCheck = gameStatus.in_check;
    this.gameMessage = gameStatus.message;

    this.updateGameStatus(
      gameStatus.status,
      gameStatus.winner,
      gameStatus.message,
      gameStatus.in_check
    );

    // 如果游戏结束，显示覆盖层
    if (gameStatus.status === "checkmate" || gameStatus.status === "stalemate") {
      this.showGameOverOverlay(gameStatus);
      
      // 禁用AI按钮
      const aiBtn = document.getElementById("aiMoveBtn");
      if (aiBtn) {
        aiBtn.disabled = true;
      }
    }
  }

  updateGameStatus(status, winner, message, inCheck) {
    const statusElement = document.getElementById("gameStatus");
    const currActiveElement = document.getElementById("currActive");

    // 移除所有状态类
    statusElement.className = "";

    console.log("更新游戏状态:", { status, message, inCheck, winner });

    switch (status) {
      case "playing":
        statusElement.className = "status-playing";
        statusElement.textContent = "游戏进行中";
        break;
        
      case "check":
        statusElement.className = "status-check";
        statusElement.textContent = message + " ⚠️";
        break;
        
      case "checkmate":
        statusElement.className = "status-checkmate";
        const checkmateWinnerText = winner === "red" ? "红方" : "黑方";
        const checkmateLoserText = winner === "red" ? "黑方" : "红方";
        statusElement.textContent = `💀 ${checkmateLoserText}被将死，${checkmateWinnerText}获胜！`;
        currActiveElement.textContent = `游戏结束 - ${checkmateWinnerText}获胜`;
        break;
        
      case "stalemate":
        statusElement.className = "status-stalemate";
        const stalemateWinnerText = winner === "red" ? "红方" : "黑方";
        const stalemateLoserText = winner === "red" ? "黑方" : "红方";
        statusElement.textContent = `🔒 ${stalemateLoserText}困毙，${stalemateWinnerText}获胜！`;
        currActiveElement.textContent = `游戏结束 - ${stalemateWinnerText}获胜（对方困毙）`;
        
        // 显示困毙特殊提示
        this.showStalemateNotification(stalemateLoserText, stalemateWinnerText);
        break;
    }

    this.inCheck = inCheck;
  }

  showStalemateNotification(loserText, winnerText) {
    const notification = document.createElement("div");
    notification.id = "stalemate-notification";
    notification.style.cssText = `
      position: fixed;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      background: rgba(0, 0, 0, 0.9);
      color: white;
      padding: 30px;
      border-radius: 15px;
      text-align: center;
      z-index: 1001;
      font-size: 18px;
      font-weight: bold;
      box-shadow: 0 8px 32px rgba(0, 0, 0, 0.5);
      border: 3px solid #ff9800;
    `;
    
    notification.innerHTML = `
      <div style="font-size: 24px; margin-bottom: 15px;">🔒 困毙局面！</div>
      <div style="margin-bottom: 10px;">${loserText}无子可走但未被将军</div>
      <div style="color: #4CAF50; font-size: 20px;">${winnerText}获胜！</div>
      <div style="margin-top: 15px; font-size: 14px; opacity: 0.8;">
        困毙是指没有合法移动的棋子，但王未被攻击的情况
      </div>
    `;
    
    document.body.appendChild(notification);
    
    // 3秒后自动消失
    setTimeout(() => {
      if (notification.parentNode) {
        notification.parentNode.removeChild(notification);
      }
    }, 4000);
  }

  showGameOverOverlay(gameStatus) {
    // 移除现有覆盖层
    const existingOverlay = document.querySelector(".game-over-overlay");
    if (existingOverlay) {
      existingOverlay.remove();
    }

    const overlay = document.createElement("div");
    overlay.className = "game-over-overlay";

    let title, message, titleColor, gameType;

    if (gameStatus.status === "checkmate") {
      const winnerText = gameStatus.winner === "red" ? "红方" : "黑方";
      const loserText = gameStatus.winner === "red" ? "黑方" : "红方";
      title = `🏆 ${winnerText}获胜！`;
      message = `${loserText}被将死`;
      titleColor = gameStatus.winner === "red" ? "#ff4444" : "#333333";
      gameType = "将死";
    } else if (gameStatus.status === "stalemate") {
      const winnerText = gameStatus.winner === "red" ? "红方" : "黑方";
      const loserText = gameStatus.winner === "red" ? "黑方" : "红方";
      title = `🔒 ${winnerText}获胜！`;
      message = `${loserText}困毙（无子可走）`;
      titleColor = gameStatus.winner === "red" ? "#ff4444" : "#333333";
      gameType = "困毙";
    }

    overlay.innerHTML = `
      <div class="game-over-title" style="color: ${titleColor}">${title}</div>
      <div class="game-over-message">${message}</div>
      <div style="font-size: 16px; margin: 15px 0; padding: 10px; background: rgba(255,255,255,0.1); border-radius: 8px;">
        胜负原因：${gameType}
      </div>
      <div class="game-over-actions">
        <button class="game-over-btn" onclick="game.resetGame()">再来一局</button>
        <button class="game-over-btn" onclick="game.hideGameOverOverlay()">查看棋谱</button>
      </div>
    `;

    document.getElementById("canvasWrap").appendChild(overlay);

    // 显示新游戏按钮
    document.getElementById("newGameBtn").style.display = "inline-block";
    document.getElementById("aiMoveBtn").style.display = "none";
  }

  hideGameOverOverlay() {
    const overlay = document.querySelector(".game-over-overlay");
    if (overlay) {
      overlay.remove();
    }
  }

  switchToPlayerControlMode(playerColor) {
    this.gameMode = "human_vs_human";
    this.currentPlayer = playerColor;

    // 更新UI显示当前玩家
    this.updatePlayerIndicator(playerColor);

    console.log(`🎮 游戏模式切换为: 玩家控制${playerColor}方`);

    // 隐藏AI按钮，因为现在是双人模式
    const aiBtn = document.getElementById("aiMoveBtn");
    if (aiBtn) {
      aiBtn.style.display = "none";
    }
  }

  updatePlayerIndicator(playerColor) {
    // 更新现有的状态显示
    const playerText = playerColor === "red" ? "红方" : "黑方";
    this.updateStatus(playerText);

    // 创建或更新游戏模式指示器
    let modeIndicator = document.getElementById("game-mode-indicator");

    if (!modeIndicator) {
      modeIndicator = document.createElement("div");
      modeIndicator.id = "game-mode-indicator";
      document.body.appendChild(modeIndicator);
    }

    if (this.gameMode === "human_vs_human") {
      modeIndicator.textContent = `双人模式 - 当前: ${playerText}`;
      modeIndicator.style.background =
        playerColor === "red"
          ? "linear-gradient(135deg, #ff4444, #cc0000)"
          : "linear-gradient(135deg, #333333, #000000)";
    } else {
      modeIndicator.textContent = "人机模式";
      modeIndicator.style.background =
        "linear-gradient(135deg, #4CAF50, #45a049)";
    }
  }

  showMessage(message, type = 'info') {
    // 查找现有的消息显示元素
    let messageEl = document.getElementById("temp-message");

    if (!messageEl) {
      // 创建临时消息元素
      messageEl = document.createElement("div");
      messageEl.id = "temp-message";
      document.body.appendChild(messageEl);
    }

    messageEl.textContent = message;
    messageEl.style.display = "block";
    
    // 根据类型设置颜色
    switch (type) {
      case 'success':
        messageEl.style.background = "rgba(76, 175, 80, 0.9)";
        break;
      case 'error':
        messageEl.style.background = "rgba(244, 67, 54, 0.9)";
        break;
      case 'warning':
        messageEl.style.background = "rgba(255, 152, 0, 0.9)";
        break;
      default:
        messageEl.style.background = "rgba(0, 0, 0, 0.9)";
    }

    // 3秒后自动隐藏
    setTimeout(() => {
      if (messageEl.textContent === message) {
        messageEl.style.display = "none";
      }
    }, 3000);
  }

  addModeToggleButton() {
    // 检查是否已存在按钮
    if (document.getElementById("mode-toggle-btn")) return;

    const toggleBtn = document.createElement("button");
    toggleBtn.id = "mode-toggle-btn";
    toggleBtn.textContent = "切换到双人模式";

    toggleBtn.onclick = () => {
      if (this.gameMode === "human_vs_ai") {
        this.gameMode = "human_vs_human";
        toggleBtn.textContent = "切换到人机模式";
        this.showMessage("已切换到双人模式");
        document.getElementById("aiMoveBtn").style.display = "none";
      } else {
        this.gameMode = "human_vs_ai";
        toggleBtn.textContent = "切换到双人模式";
        this.showMessage("已切换到人机模式");
        if (this.gameState === "playing" || this.gameState === "check") {
          document.getElementById("aiMoveBtn").style.display = "inline-block";
        }
      }
      this.updatePlayerIndicator(this.currentPlayer);
    };

    document.body.appendChild(toggleBtn);
  }

  // ===== 状态转换相关方法 =====

  boardToState() {
    let state = "";

    // 按照后端期望的顺序生成状态字符串
    const pieceOrder = [
      // 红方棋子
      { text: "車", type: "red", index: 8 },
      { text: "馬", type: "red", index: 7 },
      { text: "相", type: "red", index: 6 },
      { text: "仕", type: "red", index: 5 },
      { text: "帅", type: "red", index: 4 },
      { text: "仕", type: "red", index: 3 },
      { text: "相", type: "red", index: 2 },
      { text: "馬", type: "red", index: 1 },
      { text: "車", type: "red", index: 0 },
      { text: "炮", type: "red", index: 10 },
      { text: "炮", type: "red", index: 9 },
      { text: "兵", type: "red", index: 15 },
      { text: "兵", type: "red", index: 14 },
      { text: "兵", type: "red", index: 13 },
      { text: "兵", type: "red", index: 12 },
      { text: "兵", type: "red", index: 11 },

      // 黑方棋子
      { text: "車", type: "black", index: 16 },
      { text: "馬", type: "black", index: 17 },
      { text: "象", type: "black", index: 18 },
      { text: "士", type: "black", index: 19 },
      { text: "将", type: "black", index: 20 },
      { text: "士", type: "black", index: 21 },
      { text: "象", type: "black", index: 22 },
      { text: "馬", type: "black", index: 23 },
      { text: "車", type: "black", index: 24 },
      { text: "炮", type: "black", index: 25 },
      { text: "炮", type: "black", index: 26 },
      { text: "卒", type: "black", index: 27 },
      { text: "卒", type: "black", index: 28 },
      { text: "卒", type: "black", index: 29 },
      { text: "卒", type: "black", index: 30 },
      { text: "卒", type: "black", index: 31 },
    ];

    for (const pieceType of pieceOrder) {
      const piece = this.pieces.find((p) => p.id === pieceType.index);
      if (piece && piece.x !== 99 && piece.y !== 99) {
        state += piece.x.toString() + piece.y.toString();
      } else {
        state += "99"; // 棋子已被吃掉
      }
    }

    return state;
  }

  applyStateToBoard(state) {
    // 将64字符状态字符串应用到棋盘
    const pieces = [];
    for (let i = 0; i < state.length; i += 2) {
      pieces.push(state.substr(i, 2));
    }

    for (let i = 0; i < 32; i++) {
      const pos = pieces[i];
      if (pos === "99") {
        this.pieces[i].x = 99;
        this.pieces[i].y = 99;
      } else {
        this.pieces[i].x = parseInt(pos[0]);
        this.pieces[i].y = parseInt(pos[1]);
      }
    }
  }

  updateStatus(message) {
    document.getElementById("currActive").textContent = message;
    document.getElementById("status").textContent = message;
  }

  resetGame() {
    // 隐藏游戏结束覆盖层
    this.hideGameOverOverlay();

    // 移除困毙通知
    const stalemateNotification = document.getElementById("stalemate-notification");
    if (stalemateNotification) {
      stalemateNotification.remove();
    }

    this.initPieces();
    this.selectedPiece = null;
    this.validMoves = [];
    this.currentPlayer = "red";
    this.gameState = "playing";
    this.gameMode = "human_vs_ai";
    this.winner = null;
    this.inCheck = false;
    this.gameMessage = "游戏进行中";

    this.updateStatus("红方");
    this.updateGameStatus("playing", null, "游戏进行中", false);
    document.getElementById("aiMoveBtn").disabled = false;

    // 重新显示AI按钮，隐藏新游戏按钮
    const aiBtn = document.getElementById("aiMoveBtn");
    const newGameBtn = document.getElementById("newGameBtn");
    if (aiBtn) {
      aiBtn.style.display = "inline-block";
    }
    if (newGameBtn) {
      newGameBtn.style.display = "none";
    }

    // 更新模式切换按钮
    const toggleBtn = document.getElementById("mode-toggle-btn");
    if (toggleBtn) {
      toggleBtn.textContent = "切换到双人模式";
    }

    // 清除模式指示器
    const modeIndicator = document.getElementById("game-mode-indicator");
    if (modeIndicator) {
      modeIndicator.remove();
    }

    // 清除临时消息
    const tempMessage = document.getElementById("temp-message");
    if (tempMessage) {
      tempMessage.style.display = "none";
    }

    // 如果是REST模式，重新初始化游戏
    if (this.useRestApi) {
      this.initRestGame();
    }

    this.draw();
  }
}

// 在游戏启动时初始化
let game;
window.onload = function () {
  game = new XiangqiGame();
  
  console.log("🎮 象棋游戏已启动");
  console.log("✅ REST API模式");
};
